#!usr/lib/python
# coding:utf-8
"""
@author: jeffxun
@date  : 2012-07-03
"""

import time
import MySQLdb
import traceback
import MySQLdb.cursors

import utils.ini.ReadIni as ReadIni

#===============================================================
SQL_STATUS_FREE            =             0
SQL_STATUS_BUSZ            =             1
SQL_STATUS_ERROR           =             2
SQL_STATUS_END             =             3

class MDBServer(object):
    """ """
    instance_one = None
    
    def __new__(self, *args, **kwargs):
        if not MDBServer.instance_one:
            MDBServer.instance_one = object.__new__(self, *args, **kwargs)
        return MDBServer.instance_one
    def __init__(self,utf="utf8",dbDict=True):
        """ """
        self._uncode = utf
        self._curtype = dbDict
        self._dbConn = None
        self._dbCurs = None
        self._log = None
        self.__status = SQL_STATUS_FREE
        
    def LinkDBConf(self,dbconf):
        """ """
        conf = ReadIni.ReadIni(dbconf)
        db_host     = conf.ReadConfig("db1", "host")
        db_user     = conf.ReadConfig("db1", "user")
        db_passwd   = conf.ReadConfig("db1", "passwd")
        db_name     = conf.ReadConfig("db1", "db")
        if self._DBConnect((db_host, db_user, db_passwd, db_name), self._uncode, self._curtype):
            return self
        else:
            raise AttributeError,"MDBServer __init__ failed"
    
    def LinkDB(self,host,user,passwd,dbname):
        """ """
        if self._DBConnect((host, user, passwd, dbname), self._uncode, self._curtype):
            return self
        else:
            raise AttributeError,"MDBServer __init__ failed"
        
    def _DBConnect(self,(host,user,passwd,dbname),utf,dbDict):
        """ """
        DbType = MySQLdb.cursors.DictCursor # 查询数据显示的方式
        if not dbDict:
            DbType = MySQLdb.cursors.BaseCursor
        try:
            self._dbConn = MySQLdb.connect(host,user,passwd,dbname,charset=utf)
            self._dbCurs = self._dbConn.cursor(cursorclass = DbType)
        except:
            print traceback.format_exc()
            return False
        return True
    def closeDB(self):
        """ """
        self._dbCurs.close()
        self._dbConn.close()
        
    def runcommand(self,sql):
        """ """
        if self.__status == SQL_STATUS_FREE:
            self.__status = SQL_STATUS_BUSZ
            return self.__execute(sql)
        elif self.__status == SQL_STATUS_END:
            return "sql_server leaved"
        elif self.__status == SQL_STATUS_ERROR:
            return "sql_server error"
        elif self.__status == SQL_STATUS_BUSZ:
            time.sleep(0.1)
            return self.runcommand(sql)
        else:
            return "sql_server unkown error"
        
    def __execute(self,sql):
        """ """
        result = ""
        try:
            self.setLog(sql)
            self._dbCurs.execute(sql)
            result = self._dbCurs.fetchall()
            self._dbConn.commit()
        except:
            err =  traceback.format_exc()
            print err
            self.setLog(err,"error")
        self.__status = SQL_STATUS_FREE
        return result
        
    def select(self,sql):
        """ """
        try:
            self._dbConn.commit()
            self.setLog(sql)
            self._dbCurs.execute(sql)
            result = self._dbCurs.fetchall()
            return result
        except:
            err =  traceback.format_exc()
            print err
            self.setLog(err,"error")
        return None
    def insert(self,sql):
        """ """
        try:
            self.setLog(sql)
            self._dbCurs.execute(sql)
            self._dbConn.commit()
        except:
            err =  traceback.format_exc()
            print err
            self.setLog(err,"error")
    def update(self,sql):
        try:
            self.setLog(sql)
            self._dbCurs.execute(sql)
            self._dbConn.commit()
        except:
            err =  traceback.format_exc()
            print err
            self.setLog(err,"error")
    def delete(self,sql):
        try:
            self.setLog(sql)
            self._dbCurs.execute(sql)
            self._dbConn.commit()
        except:
            err =  traceback.format_exc()
            print err
            self.setLog(err,"error")
    def openLog(self,log):
        self._log = log
    def setLog(self,msg,ltype="debug"):
        """ """
        if self._log and ltype=="debug":
            self._log.debug(msg)
        elif self._log and ltype == "error":
            self._log.error(msg)
        elif self._log:
            self._log.waring(msg)
        else:
            print msg

if __name__=="__main__":
    a = MDBServer()
    a.LinkDB("192.168.1.245", "youyi", "youyi", "web_sanguo")
    sql = "select id,name,type,level,armtype,armnum from general where city = %s"%(369+312*4096)
    print a.runcommand(sql)